<template>
  <el-form ref="deptForm" :model="form" :rules="rules" label-width="120px">
    <el-form-item label="部门名称" prop="name">
      <el-input
        v-model="form.name"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门编码" prop="code">
      <el-input
        v-model="form.code"
        style="width: 80%"
        placeholder="1-50个字符"
      />
    </el-form-item>
    <el-form-item label="部门负责人" prop="manager">
      <el-select v-model="form.manager" style="width: 80%" placeholder="请选择">
        <el-option
          v-for="item in list"
          :key="item.id"
          :value="item.username"
          :label="item.username"
        />
      </el-select>
    </el-form-item>
    <el-form-item label="部门介绍" prop="introduce">
      <el-input
        v-model="form.introduce"
        style="width: 80%"
        placeholder="1-300个字符"
        type="textarea"
        :rows="3"
      />
    </el-form-item>
    <el-form-item>
      <el-button type="primary" size="small" @click="hSubmit">确定</el-button>
      <el-button size="small" @click="hCancel">取消</el-button>
    </el-form-item>
  </el-form>
</template>

<script>
import {
  getEmployees,
  addDepartment,
  getDepartmentDetail,
  editDepartment
} from '@/api/departments'
export default {
  props: {
    oldList: {
      type: Array,
      required: true
    },
    id: {
      type: String,
      required: true
    },
    isEdit: {
      type: Boolean,
      required: true
    }
  },
  data() {
    // 自定义校验函数(部门名称)
    const existNameValid = (rule, value, callback) => {
      let existNameList = this.oldList
        .filter((item) => item.pid === this.id)
        .map((item) => item.name)
      console.log(existNameList, 'existNameList')
      // 确认是否是编辑状态
      if (this.isEdit) {
        const pid = this.oldList.find((item) => item.id === this.id).pid
        const brothers = this.oldList.filter((item) => item.pid === pid)
        existNameList = brothers
          .filter((item) => item.id !== this.id)
          .map((item) => item.name)
      }
      if (existNameList.includes(value)) {
        callback(new Error(`部门名称: ${value}已经存在`))
      } else {
        callback()
      }
    }
    // 自定义校验函数
    const existCodeValid = (rule, value, callback) => {
      let existCodeList = this.oldList.map((item) => item.code)
      // 确定是否是编辑的状态
      if (this.isEdit) {
        existCodeList = this.oldList
          .filter((item) => item.id !== this.id)
          .map((item) => item.code)
      }
      console.log(existCodeList, 'existCodeList')
      if (existCodeList.includes(value)) {
        // 存在,校验失败
        callback(new Error(`部门编码: ${value}已经存在`))
      } else {
        // 不存在，放行
        callback()
      }
    }
    return {
      // 表单收集的数据对象
      form: {
        name: '',
        code: '',
        manager: '',
        introduce: ''
      },
      // 表单校验规则
      rules: {
        name: [
          { required: true, message: '请输入部门名称', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门名称必须为1-50个字符',
            trigger: 'blur'
          },
          { validator: existNameValid, trigger: 'blur' }
        ],
        code: [
          { required: true, message: '请输入部门编码', trigger: 'blur' },
          {
            min: 1,
            max: 50,
            message: '部门编码必须为1-50个字符',
            trigger: 'blur'
          },
          // 自定义校验函数
          {
            validator: existCodeValid,
            trigger: 'blur'
          }
        ],
        manager: [
          {
            required: true,
            message: '请选择部门负责人',
            trigger: ['blur', 'change']
          }
        ],
        introduce: [
          { required: true, message: '请输入部门介绍', trigger: 'blur' },
          {
            min: 1,
            max: 300,
            message: '部门名称必须为1-300个字符',
            trigger: 'blur'
          }
        ]
      },
      list: [] // 保存的是负责人的信息
    }
  },
  // 监听器：
  // watch: {
  // id: function(newValue, oldValue) {
  //   console.log(newValue, 'newValue')
  //   console.log(oldValue, 'oldValue')
  //   this.loadgetDepartmentDetail()
  // }
  // id: {
  //   handler: function(newValue, oldValue) {
  //     console.log(newValue, 'newValue')
  //     console.log(oldValue, 'oldValue')
  //     this.loadgetDepartmentDetail()
  //   },
  //   // 开启深度监听
  //   deep: true,
  //   // 立即加载
  //   immediate: true
  // }
  // },
  created() {
    this.loadgetEmployees()
    if (this.isEdit) {
      this.loadgetDepartmentDetail()
    }
  },
  methods: {
    // 清空表单
    resetForm() {
      this.$refs.deptForm.resetFields()
    },
    // 获取部门的详情
    async loadgetDepartmentDetail() {
      try {
        const res = await getDepartmentDetail(this.id)
        console.log(res, 'getDepartmentDetail')
        // 对表单进行数据回填
        this.from = res.data
      } catch (error) {
        console.log(error)
      }
    },
    // 获取部门负责人：
    async loadgetEmployees() {
      try {
        const res = await getEmployees()
        console.log(res, 'getEmployees')
        // 数据绑定
        this.list = res.data.data
      } catch (error) {
        console.log(error)
      }
    },
    // 实现新增子部门
    async doAdd() {
      try {
        const res = await addDepartment({ ...this.form, pid: this.id })
        console.log(res, 'addDepartment')
        // 子传父===> 关闭弹层，重新刷新页面
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    async doEdit() {
      // 实现部门编辑功能
      try {
        const res = await editDepartment(this.form)
        console.log(res, 'editDepartment')
        // 子传父===> 关闭弹层，重新刷新页面
        this.$emit('success')
      } catch (error) {
        console.log(error)
      }
    },
    hSubmit() {
      this.$refs.deptForm.validate((valid) => {
        if (!valid) return
        // 校验通过
        this.isEdit ? this.doEdit() : this.doAdd()
      })
    },
    // 点击取消
    hCancel() {
      // 关闭弹窗
      this.$emit('close')
    }
  }
}
</script>

<style>
</style>
